package com.glodon.paas.framework.registry.client.status;

import com.glodon.paas.framework.registry.client.exception.RegistryClientRuntimeException;
import com.glodon.paas.framework.registry.core.status.ClientStatus;
import com.glodon.paas.framework.registry.core.type.ClientBasic;
import org.apache.commons.lang.SerializationUtils;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * @author Don Li
 */
public class ClientStatusManager {
    private ZooKeeper zk;
    private String path;

    public ClientStatusManager() {
    }

    public void setClientStatus(ClientStatus status) {
        Stat stat = new Stat();
        try {
            ClientBasic basic = (ClientBasic) SerializationUtils.deserialize(zk.getData(path, false, stat));
            if (basic.getClientStatus() != status) {
                basic.setClientStatus(status);
                zk.setData(path, SerializationUtils.serialize(basic), stat.getVersion());
            }
        } catch (Exception e) {
            throw new RegistryClientRuntimeException(e);
        }
    }

    public void setZk(ZooKeeper zk) {
        this.zk = zk;
    }

    public void setPath(String path) {
        this.path = path;
    }
}
